package com.peng.mvvm_wan.fragments

import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import com.peng.mvvm_wan.BuildConfig
import com.peng.mvvm_wan.R
import com.peng.mvvm_wan.base.BaseFragment
import com.peng.mvvm_wan.beans.LoginBean
import com.peng.mvvm_wan.databinding.FragmentLoginBinding
import com.peng.mvvm_wan.viewmodels.LoginModel
import com.peng.safety.utils.InputManger
import com.peng.safety.utils.SnackUtil
import kotlinx.android.synthetic.main.fragment_login.*

class LoginFragment : BaseFragment<LoginModel>() {


    override fun getResourceId(): Int {
        return R.layout.fragment_login
    }

    override fun initViewModel(): LoginModel {
        return ViewModelProvider(requireActivity()).get(LoginModel::class.java)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        btn_login.setOnClickListener {
            viewModel.doLogin()
            InputManger.hideKeyBoard(requireActivity(), username)
        }
        viewModel.loginInfo.observe(requireActivity(), Observer<LoginBean> {
            if (it.id != 0) {
                SnackUtil.show("登录成功：${it.nickname}", true)
                Navigation.findNavController(btn_login).popBackStack()
                Navigation.findNavController(btn_login).navigate(R.id.listFragment)
            }
        })
        viewModel.canLogin.observeForever {
            btn_login.isEnabled = it
        }
        debugBtn.setOnClickListener {
            if (BuildConfig.DEBUG) {
                viewModel.inputUserName.value = "xiaowukonget"
                viewModel.inputPassword.value = "pc505261524~"
            }
        }

        username.onFocusChangeListener = object : View.OnFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (hasFocus && viewModel.inputUserName.value?.isEmpty() != false) {
                    viewModel.inputUserName.value = "xiaowukonget"
                    viewModel.inputPassword.value = "pc505261524~"
                }
            }

        }
    }


    override fun getBindingView(): View? {
        val binding = FragmentLoginBinding.inflate(layoutInflater)
        binding.lifecycleOwner = this
        binding.loginModel = viewModel
        return binding.root
    }
}